<?php

m2import("model/entity/WineryOrderFormEntryEntity.php");
m2import("model/entity/WineryOrderFormCatEntity.php");
m2import("model/cart/Cart.php");

/*
    Action configuration:
        <conf:action mapping="productlist" class="WineryOrderFormCatAction" methodmapping="true" bypassViewMapping="true">
        </conf:action>
*/
class FrontendProductListAction extends phpinchains_WebAction {

    function index (env $env, phpinchains_ViewMapping $mapping, phpinchains_ActionForm $actionform) {
        $categories = new WineryOrderFormCatEntity($actionform);
        $entries     = new WineryOrderFormEntryEntity($actionform);
        if ($GLOBALS['wof_cat_id'])
        	$actionform['wof_cat_id'] = $GLOBALS['wof_cat_id'];
        if ($actionform['wof_cat_id'] && $actionform['wof_cat_id'] != 'all') {
            $actionform['cat'] = $categories->findByPrimaryKey($actionform['wof_cat_id']);
            $actionform['entries'] = $entries->findBy('wofcat_id', $actionform['wof_cat_id'], array('orderby' => 'wofeno asc'));
        } else {
            $actionform['wof_cat_id'] = null;
            $actionform['entries'] = $entries->findAll(array('orderby' => 'wofeno asc'));
        }
        $cart = model_cart_Cart::getInstance();
        $actionform['subtotal']    = $cart->getSubTotal();
        $actionform['numarticles'] = $cart->getNumArticles();
    }

    function addArticle (env $env, phpinchains_ViewMapping $mapping, phpinchains_ActionForm $actionform) {
        $cart = model_cart_Cart::getInstance();
        if (!empty($actionform['wof_prod_id'])) {
            $entries = new WineryOrderFormEntryEntity($actionform);
            $a = $entries->findByPrimaryKey((int) $actionform['wof_prod_id']);
            if ($a)
                $cart->addArticle($a['id'], $a['wofeno'], $a['wofeproduct'], $a['wofeyear'], $a['wofeliter'], $a['wofeprice'], $actionform['wof_prod_qty']);
        }
        $actionform['cart'] = $cart;
        $this->dispatch('productlist::index', $actionform);
    }

    function removeArticle (env $env, phpinchains_ViewMapping $mapping, phpinchains_ActionForm $actionform) {
        $cart = model_cart_Cart::getInstance();
        if ((int) $actionform['wof_prod_id']) {
            $cart->removeArticle((int) $actionform['wof_prod_id']);
        }
        $this->dispatch('productlist::cart', $actionform);
    }

    function cart (env $env, phpinchains_ViewMapping $mapping, phpinchains_ActionForm $actionform) {
        $cart = model_cart_Cart::getInstance();
        $actionform['cart'] = $cart->dump();
        $actionform['subtotal']    = $cart->getSubTotal();
        $actionform['numarticles'] = $cart->getNumArticles();
    }
    
    function cleanCart (env $env, phpinchains_ViewMapping $mapping, phpinchains_ActionForm $actionform) {
        $cart = model_cart_Cart::getInstance();
        $cart->clear();
        $this->dispatch("productlist::cart", $actionform);
    }

    function recalcCart (env $env, phpinchains_ViewMapping $mapping, phpinchains_ActionForm $actionform) {
        if (is_array($actionform['wof_qty'])) {
            $cart = model_cart_Cart::getInstance();
            foreach ($actionform['wof_qty'] as $id => $qty)
                $cart->getArticleById($id)->setQty($qty);
        }
        $this->dispatch('productlist::cart', $actionform);
    }
    
    function order (env $env, phpinchains_ViewMapping $viewmapping, phpinchains_ActionForm $actionform) {
        $cart = model_cart_Cart::getInstance();
        $actionform['cart'] = $cart->dump();
        $actionform['subtotal']    = $cart->getSubTotal();
        $actionform['numarticles'] = $cart->getNumArticles();
    }

    function orderSend (env $env, phpinchains_ViewMapping $viewmapping, phpinchains_ActionForm $actionform) {
        $this->constrainIncomingView("productlist/order", "orderform");
    	if ($this->validate()) {
	        $cart = model_cart_Cart::getInstance();
	        $cartcontent = $cart->dump();
	        $subtotal    = $cart->getSubTotal();
	        $actionform['numarticles'] = $cart->getNumArticles();
	        $formdata = $this->getFormdata();
	        $mailHtmlBody = "
	        <h1>Ihre Bestellung bei Weingut Leonhard</h1>
	        <h2>Bestellter Warenkorb</h2>
	        <table width=\"600\">
	        	<tr>
	        		<th align=\"left\">Art-Nr.</th>
	        		<th align=\"left\">Beschreibung</th>
	        		<th align=\"right\">Preis</th>
	        		<th align=\"right\">Menge</th>
	        	</tr>";
	       	for ($i = 0; $i < count($cartcontent); $i++) {
	       		$mailHtmlBody .= '            <tr>
                <td rowspan="2" valign="top">Nr. '.$cartcontent[$i]['no'].'</td>
                <td><b>'.$cartcontent[$i]['name'].'</b></td>
                <td align="right">'.number_format($cartcontent[$i]['price'], 2, ',', ' ').' &euro;</td>
                <td align="right">'.$cartcontent[$i]['qty'].'</td>
            </tr>
            <tr>
                <td colspan="4">'.number_format($cartcontent[$i]['liter'], 3, ',', ' ').' l, Jahrgang '.$cartcontent[$i]['year'].'</td>
            </tr>
';
	       	}
	        $mailHtmlBody .= '
	        </table>
	                <br/>
        <b>enthaltene MwSt:</b> '.number_format(($subtotal - ($subtotal/1.19)),2,',','.').' &euro;<br/>
        <b>Summe:</b> '.number_format($subtotal,2,',','.').' &euro;
        <br/>
        <br/>
        <a name="form"></a>
        <h2>Bestelladresse:</h2>
        <table width="600">
        	<tr>
        		<td width="150">Name:</td>
        		<td>'.$formdata['name'].'</td>
        	</tr>
        	<tr>
        		<td>Vorname:</td>
        		<td>'.$formdata['vorname'].'</td>
        	</tr>
        	<tr>
        		<td>Firma:</td>
        		<td>'.$formdata['firma'].'</td>
        	</tr>
        	<tr>
        		<td>Stra&szlig;e / Nr.:</td>
        		<td>'.$formdata['strasse'].' '.$formdata['hausnummer'].'</td>
        	</tr>
        	<tr>
        		<td>Adresszusatz:</td>
        		<td>'.$formdata['adresszusatz'].'</td>
        	</tr>
        	<tr>
        		<td>PLZ / Ort:</td>
        		<td>'.$formdata['plz'].' '.$formdata['ort'].'</td>
        	</tr>
        	<tr>
        		<td>Land:</td>
        		<td>'.$formdata['land'].'</td>
        	</tr>
        	<tr>
        		<td>eMail:</td>
        		<td>'.$formdata['email'].'</td>
        	</tr>
        	<tr>
        		<td>Telefon:</td>
        		<td>'.$formdata['telefon'].'</td>
        	</tr>
        	<tr>
        		<td valign="top">Nachricht:</td>
        		<td>'.$formdata['nachricht'].'</td>
        	</tr>
        </table>
        '.($formdata['use_order_address']=='Y'?'
        <h2>Rechnungsadresse:</h2>
        <table width="600">
        	<tr>
        		<td width="150">Name:</td>
        		<td>'.$formdata['rech_name'].'</td>
        	</tr>
        	<tr>
        		<td>Vorname:</td>
        		<td>'.$formdata['rech_vorname'].'</td>
        	</tr>
        	<tr>
        		<td>Firma:</td>
        		<td>'.$formdata['rech_firma'].'</td>
        	</tr>
        	<tr>
        		<td>Stra&szlig;e / Nr.:</td>
        		<td>'.$formdata['rech_strasse'].' '.$formdata['rech_hausnummer'].'</td>
        	</tr>
        	<tr>
        		<td>Adresszusatz:</td>
        		<td>'.$formdata['rech_adresszusatz'].'</td>
        	</tr>
        	<tr>
        		<td>PLZ / Ort:</td>
        		<td>'.$formdata['rech_plz'].' '.$formdata['rech_ort'].'</td>
        	</tr>
        	<tr>
        		<td>Land:</td>
        		<td>'.$formdata['rech_land'].'</td>
        	</tr>
        </table>

        ':'').'
	        ';
    		m2import('phpinchains/Zend/Mail.php');
    		$mail = new Zend_Mail('UTF-8');
    		$mail->setBodyText('Sie benötigen einen HTML-fähigen Mailclient')
	    		->setBodyHtml($mailHtmlBody)
	    		->setFrom('bestellung@weingut-leonhard.de', 'Weingut Leonhard')
	    		->addTo($formdata['email'], $formdata['name'])
	    		->setSubject('Bestellung im Weinshop des Weingut Leonhard')
	    		->send();
    		$mail = new Zend_Mail('UTF-8');
    		$mail->setBodyText('Sie benötigen einen HTML-fähigen Mailclient')
	    		->setBodyHtml($mailHtmlBody.'
	    		<br/><br/>
			Vielen Dank für Ihre Bestellung.<br/>
			<b>Ihr Weingut Leonhard</b>')
	    		->setFrom('bestellung@weingut-leonhard.de', 'Weingut Leonhard')
	    		->addTo('ml@kreativburg.de', 'Marcel Linnenfelser')
	    		->setSubject('Neue Bestellung im Shop auf Weingut-Leonhard.de')
	    		->send();
    	} else {
    		$this->dispatch("productlist::order", $actionform);
    	}
    }
    
    function viewImage (env $env, phpinchains_ViewMapping $viewmapping, phpinchains_ActionForm $actionform) {
        $actionform->set('rootAction', 'viewBlob');
        $actionform->set("content-disposition", "inline");
        $actionform['field'] = 'wofeimg';
        $this->_handleBlob ($env, $viewmapping, $actionform);
    }

    function _handleBlob (env $env, phpinchains_ViewMapping $viewmapping, phpinchains_ActionForm $actionform) {
        ob_clean();
        $field = $actionform['field'];
        if ($id = (int) $actionform->get("id")) {
            $entity = new WineryOrderFormEntryEntity($actionform, null);
            if (!$entity->isBlob($field)) {
                $this->setResponse("given field is not a blob!");
            }
            $displayObj = $entity->findByPrimaryKey((int) $actionform->get("id"), array("fields" => "$field,{$field}_type,{$field}_size,{$field}_filename"));
            if ($actionform->get("content-disposition") == "attachment") {
                if($env->getServer("HTTP_USER_AGENT") and strpos($env->getServer("HTTP_USER_AGENT"),"MSIE"))
                    header("Content-Type: application/force-download");
                else
                    Header("Content-Type: application/octet-stream");
            } else {
                header("Content-Type: ".$displayObj["{$field}_type"]);
            }
            if (($resizeW = (int)$actionform->get('resize')) && preg_match('/image/i', $displayObj["{$field}_type"])) {
                try {
                    header("Content-disposition: ".$actionform->get("content-disposition")."; filename=".$displayObj["{$field}_filename"]);
                    header("Cache-Control: max-age=3600, must-revalidate");
                    header("Expires: " . gmdate("D, d M Y H:i:s", time()+86400) . " GMT");
                    header("Pragma: cache");
                    $source = @imagecreatefromstring($displayObj[$field]);
                    $width  = @imagesx($source);
                    if ($width <= $resizeW) {
                        /*header("Content-Length: ".$displayObj["{$field}_size"]);
                        $this->setResponse($displayObj[$field]);
                        return;*/
                        $resizeW = $width;
                    }
                    $height = @imagesy($source);
                    $newwidth  = $resizeW;
                    $newheight = round($height * ($resizeW / $width));
                    $thumb = imagecreatetruecolor($newwidth, $newheight);
                    imagecopyresampled($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
                    if (preg_match('/gif$/i', $displayObj["{$field}_type"])) {
                        imagegif($thumb);
                    } elseif (preg_match('/png$/i', $displayObj["{$field}_type"])) {
                        imagepng($thumb);
                    } else {
                        imagejpeg($thumb);
                    }
                    $this->setResponse('');
                } catch (Exception $e) {}
            } else {
                header("Content-Length: ".$displayObj["{$field}_size"]);
                header("Content-disposition: ".$actionform->get("content-disposition")."; filename=".$displayObj["{$field}_filename"]);
                $this->setResponse($displayObj[$field]);
            }
        } else {
            $env->setAttribute("actionmsg", "actionmsg_no_id_download");
            $this->setResponse("no image available");
        }
        exit;
    }


}


?>